package com.qian.fmall.user.controller;

import com.qian.fmall.commons.ResultSet;
import com.qian.fmall.commons.utils.Constant;
import com.qian.fmall.commons.utils.MD5Utils;
import com.qian.fmall.user.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @DubboReference
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RequestMapping("/login")
    public ResultSet userLogin(String username,String password)
    {
        System.out.println(username+"-----"+password);
        return userService.userLogin(username,password);
    }
    @RequestMapping("checkLogin")
    public ResultSet checkLogin(String token,String username)
    {
        if(StringUtils.isEmpty(token))
        {
            return ResultSet.error("token为空");
        }
        try{
            ValueOperations ov = redisTemplate.opsForValue();
            String key= Constant.KEY_HEAD + username;
            String o =ov.get(key).toString().replace("\"","");
            JwtParser parser = Jwts.parser();
            parser.setSigningKey(MD5Utils.md5(MD5Utils.md5(o)));
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            String username1 = body.get("username", String.class);
            return ResultSet.ok("success");
        }
        catch (Exception  e)
        {
            return ResultSet.error("token非法");
        }
    }
    @RequestMapping("address")
    public ResultSet getAddressByUserId(String userId)
    {
        return userService.getAddr(userId);
    }
}
